package com.zxy.ziems.server.web;

import com.zxy.btp.common.response.JsonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应结果（ResponseBody）处理器
 *
 * @author chdzq
 * @create 2022/11/11
 */
@ControllerAdvice
public class GlobalResponseBodyHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (null ==  returnType.getMethod()) {
            return false;
        }
        // 只拦截返回结果为 Result 类型
        IgnoreJsonResponse skipAnnotation = returnType.getMethod().getAnnotation(IgnoreJsonResponse.class);
        if (null != skipAnnotation) {
            return false;
        }
        Class<?> type = returnType.getParameterType();
        return  !JsonResponse.class.isAssignableFrom(type)
                && !ModelAndView.class.isAssignableFrom(type);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (selectedContentType == MediaType.APPLICATION_OCTET_STREAM) {
            return body;
        }
        // 记录 Controller 结果
        Class<?> type = returnType.getParameterType();
        if (JsonResponse.class.isAssignableFrom(type)) {
            return body;
        } else {
            return JsonResponse.SUCCESS(body);
        }
    }
}
